package com.weixin.project.Config.Filter;

import com.weixin.project.Entity.User;
import com.weixin.project.Service.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

public class CurrentUserFilter extends OncePerRequestFilter {

    private final UserService userService;
    public CurrentUserFilter(UserService userService){
        this.userService = userService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        System.out.println("received request: " + request.getRequestURI());
        //打印所有请求header
//        Enumeration<String> headerNames = request.getHeaderNames();
//        System.out.println("===============================");
//        while (headerNames.hasMoreElements()) {
//            String headerName = headerNames.nextElement();
//            System.out.println(headerName + ": " + request.getHeader(headerName));
//        }
//        System.out.println("===============================");
//        String userId = request.getHeader("user_id");
        String userId = request.getHeader("token");
        System.out.println("user_id:" + userId);
        if (!isExcludedPath(request.getRequestURI())) {
            if (userId == null || userService.findCurrentUser(userId) == null) {
                response.sendError(HttpStatus.BAD_REQUEST.value(), "Missing or invalid userId in request header");
                return;
            }

            // get user info from token or session or cookie
            request.setAttribute("current_user", userService.findCurrentUser(userId));
        }
        filterChain.doFilter(request, response);
    }

    private boolean isExcludedPath(String path){
        //登录不需要携带userId参数
        if (path.startsWith("/login")) return true;
        //用于测试的接口不需要携带userId参数
        if (path.equals("/test/login") || path.equals("/test/addpractices")) return true;
        //查看图片不需要携带userId参数
        if (path.startsWith("/images")) return true;
        //查看json文件不需要携带userId参数
        if (path.startsWith("/json")) return true;
        //查看所有路由不需要携带userId参数
        if (path.equals("/mappings")) return true;
        //查看视频路由不需要携带userId参数
        if (path.startsWith("/download-video")) return true;
        //查看hello不需要携带userId参数
        if (path.startsWith("/hello")) return true;
        return false;
    }
}
